package cn.iocoder.yudao.module.xkfz.util;

import cn.iocoder.yudao.framework.common.exception.ServiceException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.List;

public class ValidationUtil {

    private static final Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    /**
     * 校验对象或者 List 集合中的所有元素
     *
     * @param object  需要校验的对象或列表
     * @param groups  校验分组
     * @throws IllegalArgumentException 如果校验失败
     */
    public static <T> void validate(T object, Class<?>... groups) {
        if (object == null) {
            throw new ServiceException(10001,"校验对象不能为空");
        }

        if (object instanceof List) {
            // 递归校验 List<T> 里面的每个元素
            List<?> list = (List<?>) object;
            for (Object item : list) {
                validate(item, groups);
            }
        } else {
            // 校验单个对象
            Set<ConstraintViolation<T>> violations = validator.validate(object, groups);
            if (!violations.isEmpty()) {
                String errorMessage = violations.stream()
                        .map(ConstraintViolation::getMessage)
                        .collect(Collectors.joining("; "));

                throw new ServiceException(10001,"参数校验失败: " + errorMessage);
            }
        }
    }
}
